package com.qingmu.club.minaapi.controller.member;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qingmu.club.minaapi.model.QueryShopModel;
import com.qingmu.club.minaapi.plus.entity.*;
import com.qingmu.club.minaapi.custom.logic.ClubShopLogic;
import com.qingmu.club.minaapi.custom.logic.ClubUsersLogic;
import com.qingmu.club.minaapi.plus.service.*;
import com.qingmu.club.minaapi.utils.KeyValueDefine;
import com.qingmu.club.minaapi.utils.ResponseObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;

/**
 * <p>
 * 俱乐部主表 前端控制器
 * </p>
 *
 * @author duke
 * @since 2019-08-20
 */
@RestController
@CrossOrigin(origins = "*", methods = {RequestMethod.POST, RequestMethod.GET})
@Api(value = "俱乐部门店相关(会员端小程序)", description = "俱乐部门店相关(会员端小程序)")
@RequestMapping("/member/clubShop")
public class MemberClubShopController {

    @Autowired
    ClubShopLogic clubShopLogic;

    @Autowired
    ClubUsersLogic clubUsersLogic;

    @Autowired
    ClubShopService clubShopService;

    @Autowired
    ClubUsersService clubUsersService;

    @Autowired
    ClubService clubService;

    @Autowired
    UsersService usersService;

    @Autowired
    IntegralSharePresentService integralSharePresentService;

    @Autowired
    ClubUsersIntegralService clubUsersIntegralService;

    @Autowired
    IntegralAttentionPresentService integralAttentionPresentService;

    @RequestMapping(value = "/selectNearby", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ApiOperation(value = "查询附近门店")
    public ResponseEntity select(
            @ApiParam(required = false, value = "当前页", example = "1") @RequestParam(required = false) Integer page,
            @ApiParam(required = false, value = "每页数量", example = "10") @RequestParam(required = false) Integer pageSize,
            @ApiParam(required = false, value = "用户id") @RequestParam(required = false) String userId,
            @ApiParam(required = false, value = "门店名称") @RequestParam(required = false) String shopName,
            @ApiParam(required = true, value = "经度") @RequestParam(required = true) Double longitude,
            @ApiParam(required = true, value = "纬度") @RequestParam(required = true) Double latitude
    ) {
        HashMap<String, Object> map = clubShopLogic.queryNearByShop(shopName,latitude, longitude, page, pageSize,userId);

        return ResponseObject.success(map);
    }

    @RequestMapping(value = "/getById", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ApiOperation(value = "查询门店详情")
    public ResponseEntity getById(
            @ApiParam(required = true, value = "门店id") @RequestParam(required = true) String shopId,
            @ApiParam(required = false, value = "会员id") @RequestParam(required = false) String userId
    ) {
        Users users = this.usersService.getById(userId);

        ClubShop clubShop = this.clubShopService.getById(shopId);
        if (clubShop == null) {
            return  ResponseObject.error(601,"门店不存在");
        }

        Boolean attention = false;
        if (users != null) {
            ClubUsers clubUsers = this.clubUsersLogic.getUserShop(shopId, userId);
            if (clubUsers != null) {
                attention = true;
            }
        }
        Club club =this.clubService.getById(clubShop.getClubId());
        int fansSum = clubUsersLogic.queryUserSum(shopId);

        QueryShopModel shopModel = new QueryShopModel();
        BeanUtils.copyProperties(clubShop, shopModel);
        shopModel.setFansSum(fansSum);
        shopModel.setAttention(attention);
        shopModel.setClubPhone(club.getClubPhone());

        return ResponseObject.success(shopModel);
    }


    @RequestMapping(value = "/updateAttention", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ApiOperation(value = "用户关注门店 取消门店")
    public ResponseEntity updateAttention(
            @ApiParam(required = true, value = "门店id") @RequestParam(required = true) String shopId,
            @ApiParam(required = true, value = "会员id") @RequestParam(required = true) String userId,
            @ApiParam(required = true, value = "true关注 false取消关注") @RequestParam(required = true) boolean attention,
            @ApiParam(required = false, value = "用户分享id") @RequestParam(required = false) String recommendId
    ) {
        Users users = this.usersService.getById(userId);
        if(users==null){
            return ResponseObject.error(401,"会员信息找不到");
        }

        if(StringUtils.isEmpty(users.getUserName()) && StringUtils.isEmpty(users.getUserSex()) && StringUtils.isEmpty(users.getUserIcon())){
            return ResponseObject.error(408,"请授权会员信息");
        }

        ClubShop clubShop = this.clubShopService.getById(shopId);
        if (clubShop == null) {
            return  ResponseObject.error(601,"门店不存在");
        }

        Integer attentionStatus = 0 ;//取消关注
        if(attention){
            attentionStatus=1;//关注
        }

        QueryWrapper<IntegralAttentionPresent> queryWrapper3 = new QueryWrapper<>();
        queryWrapper3
                .eq(IntegralAttentionPresent.CLUB_ID, clubShop.getClubId())
                .eq(IntegralAttentionPresent.STATUS, KeyValueDefine.ONLINE_STATUS);
        IntegralAttentionPresent attentionPresent = this.integralAttentionPresentService.getOne(queryWrapper3);
        Integer userJf = 0 ;
        if (attentionPresent != null) {
            userJf=attentionPresent.getPresentIntegral();
        }

        //如果会员已经关注该门店 那么直接返回成功
        QueryWrapper<ClubUsers> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(ClubUsers.SHOP_ID,shopId).eq(ClubUsers.USER_ID,userId);//关注
        ClubUsers clubUsers = this.clubUsersService.getOne(queryWrapper);
        if(clubUsers!=null) {
            clubUsers.setAttentionStatus(attentionStatus);
            boolean state = this.clubUsersService.updateById(clubUsers);
            if (!state) {
                return ResponseObject.error();
            }
            return ResponseObject.success();
        }

        ClubUsers newClubUsers = new ClubUsers();
        newClubUsers.setUserId(users.getId());
        newClubUsers.setUserName(users.getUserName());
        newClubUsers.setUserSex(users.getUserSex());
        newClubUsers.setClubId(clubShop.getClubId());
        newClubUsers.setShopId(shopId);
        newClubUsers.setShopName(clubShop.getShopName());
        newClubUsers.setShopAvater(clubShop.getCover1());
        newClubUsers.setAttentionTime(new Date());
        newClubUsers.setAttentionStatus(attentionStatus);
        newClubUsers.setUserShowStatus(KeyValueDefine.LATENT);//潜在学员
        newClubUsers.setUserIcon(users.getUserIcon());
        newClubUsers.setStatus(KeyValueDefine.ONLINE_STATUS);//默认启用
        newClubUsers.setAttentionType(KeyValueDefine.ATTENTION_SHOP);
        newClubUsers.setUserJf(userJf);
        newClubUsers.setUserMobile(users.getUserMobile());
        boolean state = this.clubUsersService.save(newClubUsers);
        if (!state) {
            return ResponseObject.error();
        }

        ClubUsersIntegral clubUsersIntegral = new ClubUsersIntegral();
        clubUsersIntegral.setIntegralName("关注积分");
        clubUsersIntegral.setClubUsersId(newClubUsers.getId());
        clubUsersIntegral.setUserId(userId);
        clubUsersIntegral.setShopId(shopId);
        clubUsersIntegral.setIntegralNum(userJf);//关注积分
        clubUsersIntegral.setType(KeyValueDefine.JF_ADD);//积分增加
        clubUsersIntegral.setGoodsImage(KeyValueDefine.JFICON);//积分记录icon
        clubUsersIntegral.setIntegralType(KeyValueDefine.JF_AUTO_CHANGE);//系统自动操作
        clubUsersIntegral.setIntegralChangeType(KeyValueDefine.SHARE_ATTENTION); //分享得积分
        boolean state2 = clubUsersIntegralService.save(clubUsersIntegral);
        if (!state2) {
            return ResponseObject.error();
        }

        //分享出去后，其他用户查看门店并关注门店，分享用户获得的积分数
        if(!StringUtils.isEmpty(recommendId)) {

            QueryWrapper<IntegralSharePresent> queryWrapper4 = new QueryWrapper<>();
            queryWrapper4.eq(IntegralSharePresent.CLUB_ID, clubShop.getClubId());
            IntegralSharePresent sharePresent = this.integralSharePresentService.getOne(queryWrapper4);
            if (sharePresent == null) {
                return ResponseObject.success(); //如果中台没设置积分赠送规则 直接返回一个空对象 不报错
            }

            QueryWrapper<ClubUsers> clubUsersQueryWrapper2 = new QueryWrapper<>();
            clubUsersQueryWrapper2.eq(ClubUsers.SHOP_ID, shopId).eq(ClubUsers.USER_ID, recommendId);//关注
            ClubUsers clubUsers2 = this.clubUsersService.getOne(clubUsersQueryWrapper2);

            String clubUsersId = "";
            if(clubUsers2==null){
                Users users2 = this.usersService.getById(recommendId);
                ClubUsers newClubUsers2 = new ClubUsers();
                newClubUsers2.setUserId(users2.getId());
                newClubUsers2.setUserName(users2.getUserName());
                newClubUsers2.setUserSex(users2.getUserSex());
                newClubUsers2.setClubId(clubShop.getClubId());
                newClubUsers2.setShopId(shopId);
                newClubUsers2.setShopName(clubShop.getShopName());
                newClubUsers2.setShopAvater(clubShop.getCover1());
                newClubUsers2.setAttentionTime(new Date());
                newClubUsers2.setAttentionStatus(KeyValueDefine.ATTENTION);//关注
                newClubUsers2.setUserShowStatus(KeyValueDefine.LATENT);//潜在学员
                newClubUsers2.setUserIcon(users2.getUserIcon());
                newClubUsers2.setStatus(KeyValueDefine.ONLINE_STATUS);//默认启用
                newClubUsers2.setAttentionType(KeyValueDefine.ATTENTION_SHOP);

                newClubUsers2.setUserJf(sharePresent.getAttentionIntegral());
                boolean state3 = this.clubUsersService.save(newClubUsers2);
                if (!state3) {
                    return ResponseObject.error();
                }
                clubUsersId=newClubUsers2.getId();
            }else {
                clubUsersId=clubUsers2.getId();
                clubUsers2.setUserJf(clubUsers2.getUserJf()+sharePresent.getAttentionIntegral());
                boolean state4 = this.clubUsersService.updateById(clubUsers2);
                if (!state4) {
                    return ResponseObject.error();
                }
            }
            ClubUsersIntegral recommend = new ClubUsersIntegral();
            recommend.setIntegralName("关注积分");
            recommend.setClubUsersId(clubUsersId);
            recommend.setUserId(recommendId);
            recommend.setShopId(shopId);
            recommend.setIntegralNum(sharePresent.getAttentionIntegral());//关注积分
            recommend.setType(1);
            recommend.setGoodsImage(KeyValueDefine.JFICON);//积分记录icon
            recommend.setIntegralType(KeyValueDefine.JF_AUTO_CHANGE);//系统自动操作
            recommend.setIntegralChangeType(KeyValueDefine.SHARE_ATTENTION); //分享得积分
            boolean state3 = clubUsersIntegralService.save(recommend);
            if (!state3) {
                return ResponseObject.error();
            }

        }

        return ResponseObject.success();
    }
}


